const fs = require('fs');
const path = require('path');
const axios = require('axios');

// 读取JSON文件
const jsonFilePath = './output/websocket_data_2025-08-27T09-16-02-098Z.json';
const outputDir = './fujiang-img';

// 确保输出目录存在
if (!fs.existsSync(outputDir)) {
  fs.mkdirSync(outputDir, { recursive: true });
}

// 读取JSON数据
const rawData = fs.readFileSync(jsonFilePath, 'utf8');
const data = JSON.parse(rawData);

// 去重并提取唯一的副将名称
const uniqueNames = [...new Set(data.map(item => item.name))];

// 只测试前5个副将
const testNames = uniqueNames.slice(0, 5);

console.log(`测试前 ${testNames.length} 个副将名称`);

// 更准确的中文转拼音映射表
function chineseToPinyin(chineseName) {
  const nameMap = {
    '南华仙人': 'nanhuaxianren',
    '童渊': 'tongyuan',
    '孙寒华': 'sunhanhua',
    '水镜先生': 'shuijingxiansheng',
    '甘宁': 'ganning',
    '司马懿': 'simayi',
    '贾诩': 'jiaxu',
    '许褚': 'xuchu',
    '郭嘉': 'guojia',
    '甄洛': 'zhenluo',
    '周瑜': 'zhouyu',
    '张飞': 'zhangfei',
    '魏延': 'weiyan',
    '黄月英': 'huangyueying',
    '陆逊': 'luxun',
    '庞统': 'pangtong',
    '马超': 'machao',
    '小姐姐': 'xiaojiejie',
    '徐庶': 'xushu',
    '孙策': 'sunce',
    '张辽': 'zhangliao',
    '黄忠': 'huangzhong',
    '赵云': 'zhaoyun',
    '吕布': 'lvbu',
    '貂蝉': 'diaohan',
    '曹操': 'caocao',
    '关羽': 'guanyu',
    '小哥哥': 'xiaogege',
    '孟获': 'menghuo',
    '祝融': 'zhurong'
  };

  // 如果直接映射存在，使用直接映射
  if (nameMap[chineseName]) {
    return nameMap[chineseName];
  }

  // 否则使用字符映射
  const charMap = {
    '南': 'nan', '华': 'hua', '仙': 'xian', '人': 'ren',
    '童': 'tong', '渊': 'yuan', '孙': 'sun', '寒': 'han',
    '水': 'shui', '镜': 'jing', '先': 'xian', '生': 'sheng',
    '甘': 'gan', '宁': 'ning', '司': 'si', '马': 'ma', '懿': 'yi',
    '贾': 'jia', '诩': 'xu', '许': 'xu', '褚': 'chu',
    '郭': 'guo', '嘉': 'jia', '甄': 'zhen', '洛': 'luo',
    '周': 'zhou', '瑜': 'yu', '张': 'zhang', '飞': 'fei',
    '魏': 'wei', '延': 'yan', '黄': 'huang', '月': 'yue', '英': 'ying',
    '陆': 'lu', '逊': 'xun', '庞': 'pang', '统': 'tong',
    '超': 'chao', '小': 'xiao', '姐': 'jie', '哥': 'ge',
    '徐': 'xu', '庶': 'shu', '策': 'ce', '辽': 'liao',
    '忠': 'zhong', '云': 'yun', '吕': 'lv', '布': 'bu',
    '貂': 'diao', '蝉': 'chan', '曹': 'cao', '操': 'cao',
    '关': 'guan', '羽': 'yu', '孟': 'meng', '获': 'huo',
    '祝': 'zhu', '融': 'rong', '蔡': 'cai', '文': 'wen', '姬': 'ji',
    '夏': 'xia', '侯': 'hou', '敦': 'dun', '蒙': 'meng',
    '鲁': 'lu', '肃': 'su', '角': 'jiao', '晃': 'huang',
    '渊': 'yuan', '宫': 'gong', '荀': 'xun', '攸': 'you',
    '玲': 'ling', '琦': 'qi', '程': 'cheng', '普': 'pu',
    '乔': 'qiao', '瑾': 'jin', '仁': 'ren', '岱': 'dai',
    '谡': 'su', '丕': 'pi', '盛': 'sheng', '大': 'da',
    '管': 'guan', '亥': 'hai', '恪': 'ke', '任': 'ren',
    '高': 'gao', '顺': 'shun', '凤': 'feng', '尚': 'shang',
    '香': 'xiang', '宝': 'bao', '索': 'suo', '异': 'yi',
    '苞': 'bao', '彰': 'zhang', '当': 'dang', '梁': 'liang',
    '腾': 'teng', '昭': 'zhao', '统': 'tong', '盖': 'gai',
    '登': 'deng', '洪': 'hong', '遂': 'sui', '竺': 'zhu',
    '典': 'dian', '邈': 'miao', '成': 'cheng',
    '霸': 'ba', '睿': 'rui', '续': 'xu', '平': 'ping',
    '师': 'shi', '璋': 'zhang', '茂': 'mao',
    '班': 'ban', '冲': 'chong', '夫': 'fu', '圭': 'gui',
    '观': 'guan', '皎': 'jiao', '休': 'xiu', '然': 'ran',
    '铁': 'tie', '远': 'yuan', '志': 'zhi', '植': 'zhi',
    '纯': 'chun', '雍': 'yong', '宜': 'yi', '遗': 'yi',
    '真': 'zhen', '琮': 'cong', '玩': 'wan', '双': 'shuang',
    '宪': 'xian', '糜': 'mi', '治': 'zhi',
    '昂': 'ang', '匡': 'kuang', '范': 'fan', '广': 'guang',
    '辟': 'pi', '瑁': 'mao', '白': 'bai', '虎': 'hu',
    '静': 'jing', '兴': 'xing', '秋': 'qiu', '豹': 'bao',
    '朗': 'lang', '春': 'chun', '华': 'hua'
  };

  let result = '';
  for (let char of chineseName) {
    if (charMap[char]) {
      result += charMap[char];
    } else {
      // 对于未映射的字符，使用简单的音译
      result += char.toLowerCase();
    }
  }
  
  return result.toLowerCase();
}

// 下载图片的函数（带重试机制）
async function downloadImageWithRetry(url, filename, maxRetries = 2) {
  let lastError = null;
  
  for (let attempt = 1; attempt <= maxRetries + 1; attempt++) {
    try {
      console.log(`  尝试 ${attempt}/${maxRetries + 1}: ${url}`);
      
      const response = await axios({
        method: 'GET',
        url: url,
        responseType: 'stream',
        timeout: 10000, // 10秒超时
      });

      const writer = fs.createWriteStream(filename);
      response.data.pipe(writer);

      return new Promise((resolve, reject) => {
        writer.on('finish', () => {
          console.log(`  ✓ 第${attempt}次尝试成功`);
          resolve();
        });
        writer.on('error', reject);
      });
    } catch (error) {
      lastError = error;
      console.log(`  ✗ 第${attempt}次尝试失败: ${error.message}`);
      
      if (attempt <= maxRetries) {
        // 等待一段时间后重试
        const delay = attempt * 1000; // 递增延迟：1秒、2秒
        console.log(`  等待 ${delay}ms 后重试...`);
        await new Promise(resolve => setTimeout(resolve, delay));
      }
    }
  }
  
  // 所有重试都失败了
  throw new Error(`经过${maxRetries + 1}次尝试后仍然失败: ${lastError.message}`);
}

// 主函数
async function main() {
  let successCount = 0;
  let failCount = 0;
  const failedNames = [];

  console.log('开始测试重试机制...\n');

  for (let i = 0; i < testNames.length; i++) {
    const name = testNames[i];
    const pinyinName = chineseToPinyin(name);
    const imageUrl = `http://cd521.xin/fujiangfull/fujiang_${pinyinName}.png`;
    const filename = path.join(outputDir, `fujiang_${pinyinName}.png`);

    console.log(`[${i + 1}/${testNames.length}] 正在下载: ${name} (${pinyinName})`);

    try {
      await downloadImageWithRetry(imageUrl, filename);
      console.log(`✓ 成功下载: ${filename}`);
      successCount++;
    } catch (error) {
      console.log(`✗ 最终失败: ${name} - ${error.message}`);
      failCount++;
      
      // 记录详细的失败信息
      const failureInfo = {
        name: name,
        pinyinName: pinyinName,
        url: imageUrl,
        filename: filename,
        error: error.message,
        timestamp: new Date().toISOString(),
        attempts: 3 // 1次初始尝试 + 2次重试
      };
      
      failedNames.push(failureInfo);
    }

    // 添加延迟避免请求过于频繁
    await new Promise(resolve => setTimeout(resolve, 500));
  }

  // 输出统计结果
  console.log('\n=== 测试完成 ===');
  console.log(`测试数量: ${testNames.length}`);
  console.log(`成功: ${successCount}`);
  console.log(`失败: ${failCount}`);

  if (failedNames.length > 0) {
    console.log('\n失败的副将:');
    failedNames.forEach((item, index) => {
      console.log(`${index + 1}. ${item.name} (${item.pinyinName})`);
      console.log(`   URL: ${item.url}`);
      console.log(`   错误: ${item.error}`);
      console.log(`   时间: ${item.timestamp}`);
      console.log('');
    });

    // 保存详细的失败列表到JSON文件
    const failedListPath = path.join(outputDir, 'test_failed_downloads.json');
    const failureReport = {
      summary: {
        totalAttempts: testNames.length,
        successCount: successCount,
        failureCount: failCount,
        successRate: ((successCount / testNames.length) * 100).toFixed(2) + '%',
        timestamp: new Date().toISOString()
      },
      failures: failedNames
    };
    
    fs.writeFileSync(failedListPath, JSON.stringify(failureReport, null, 2), 'utf8');
    console.log(`测试失败报告已保存到: ${failedListPath}`);
  }
}

// 运行主函数
main().catch(console.error);
